<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import axios from 'axios'

// 定义比赛信息接口
interface Game {
  gamesId: number
  quaId: number
  orId: number
  gameName: string
  createTime: string
  appTime: string | null
  readyTime: string | null
  startTime: string | null
  endTime: string | null
  synopsis: string | null
  attachment: string | null
}

// 响应式数据
const gameData = ref<Game>({
  gamesId: 0,
  quaId: 0,
  orId: 0,
  gameName: '',
  createTime: '',
  appTime: null,
  readyTime: null,
  startTime: null,
  endTime: null,
  synopsis: null,
  attachment: null
})

// 接收比赛对象
const props = defineProps<{
  game: Game | null
}>()

// 格式化日期时间以适配datetime-local输入框
const formatDateTimeForInput = (dateString: string | null): string | null => {
  if (!dateString) return null
  // 从ISO字符串中提取日期和时间部分 (YYYY-MM-DDTHH:mm)
  return dateString.substring(0, 16)
}

// 获取比赛详细信息
const fetchGameData = async (id: number) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(`http://localhost:8080/game/getGameById/${id}`, {
      headers: {
        'token': token || ''
      }
    })
    
    // 将获取到的数据赋值给gameData
    gameData.value = response.data
    
    // 处理日期格式，确保它们符合datetime-local输入的要求
    gameData.value.appTime = formatDateTimeForInput(gameData.value.appTime)
    gameData.value.readyTime = formatDateTimeForInput(gameData.value.readyTime)
    gameData.value.startTime = formatDateTimeForInput(gameData.value.startTime)
    gameData.value.endTime = formatDateTimeForInput(gameData.value.endTime)
    
    // 强制更新gameName字段，确保表单能正确显示
    gameData.value.gameName = response.data.gameName
  } catch (err) {
    console.error('获取比赛信息失败:', err)
  }
}

// 保存比赛信息
const saveGameInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    
    // 准备要提交的数据
    const gameToSubmit = {
      gamesId: gameData.value.gamesId,
      gameName: gameData.value.gameName,
      appTime: gameData.value.appTime,
      readyTime: gameData.value.readyTime,
      startTime: gameData.value.startTime,
      endTime: gameData.value.endTime,
      synopsis: gameData.value.synopsis
    }
    
    // 发送更新请求到服务器
    await axios.put('http://localhost:8080/game/updateGameInfo', gameToSubmit, {
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    })
    
    console.log('比赛信息保存成功')
    // 保存完成后发送事件返回比赛列表
    const event = new CustomEvent('showGameEvent', { 
      detail: { type: 'backToList' } 
    })
    window.dispatchEvent(event)
  } catch (err) {
    console.error('保存比赛信息失败:', err)
  }
}

// 取消按钮处理函数
const cancel = () => {
  // 发送事件返回比赛列表
  const event = new CustomEvent('showGameEvent', { 
    detail: { type: 'backToList' 
  }})
  window.dispatchEvent(event)
}

// 组件挂载时设置数据
onMounted(() => {
  if (props.game) {
    // 如果传入了比赛对象，直接使用它填充表单
    gameData.value = { ...props.game }
    
    // 处理日期格式，确保它们符合datetime-local输入的要求
    gameData.value.appTime = formatDateTimeForInput(gameData.value.appTime)
    gameData.value.readyTime = formatDateTimeForInput(gameData.value.readyTime)
    gameData.value.startTime = formatDateTimeForInput(gameData.value.startTime)
    gameData.value.endTime = formatDateTimeForInput(gameData.value.endTime)
  } else {
    // 如果是新建模式，则重置表单
    gameData.value = {
      gamesId: 0,
      quaId: 0,
      orId: 0,
      gameName: '',
      createTime: '',
      appTime: null,
      readyTime: null,
      startTime: null,
      endTime: null,
      synopsis: null,
      attachment: null
    }
  }
})

// 监听 game 的变化，确保在从新建模式切换到编辑模式时能正确获取数据
watch(() => props.game, (newGame) => {
  if (newGame) {
    // 如果传入了比赛对象，直接使用它填充表单
    gameData.value = { ...newGame }
    
    // 处理日期格式，确保它们符合datetime-local输入的要求
    gameData.value.appTime = formatDateTimeForInput(gameData.value.appTime)
    gameData.value.readyTime = formatDateTimeForInput(gameData.value.readyTime)
    gameData.value.startTime = formatDateTimeForInput(gameData.value.startTime)
    gameData.value.endTime = formatDateTimeForInput(gameData.value.endTime)
  } else {
    // 如果是新建模式，则重置表单
    gameData.value = {
      gamesId: 0,
      quaId: 0,
      orId: 0,
      gameName: '',
      createTime: '',
      appTime: null,
      readyTime: null,
      startTime: null,
      endTime: null,
      synopsis: null,
      attachment: null
    }
  }
}, { immediate: true })
</script>

<template>
  <div class="change-game-info">
    <form @submit.prevent="saveGameInfo" class="game-form">
      <!-- 比赛名称 -->
      <div class="form-group">
        <label for="gameName">比赛名称:</label>
        <input 
          id="gameName" 
          v-model="gameData.gameName" 
          type="text" 
          required 
          class="form-control"
        />
      </div>
      
      <!-- 时间选择（田字格布局） -->
      <div class="time-grid">
        <div class="form-group">
          <label for="appTime">报名时间:</label>
          <input 
            id="appTime" 
            v-model="gameData.appTime" 
            type="datetime-local" 
            class="form-control"
          />
        </div>
        <div class="form-group">
          <label for="readyTime">准备时间:</label>
          <input 
            id="readyTime" 
            v-model="gameData.readyTime" 
            type="datetime-local" 
            class="form-control"
          />
        </div>
        <div class="form-group">
          <label for="startTime">开始时间:</label>
          <input 
            id="startTime" 
            v-model="gameData.startTime" 
            type="datetime-local" 
            class="form-control"
          />
        </div>
        <div class="form-group">
          <label for="endTime">结束时间:</label>
          <input 
            id="endTime" 
            v-model="gameData.endTime" 
            type="datetime-local" 
            class="form-control"
          />
        </div>
      </div>
      
      <!-- 比赛简介 -->
      <div class="form-group">
        <label for="synopsis">比赛简介:</label>
        <textarea 
          id="synopsis" 
          v-model="gameData.synopsis" 
          rows="4" 
          class="form-control"
        ></textarea>
      </div>
      
      <!-- 操作按钮 -->
      <div class="form-actions">
        <button type="button" @click="saveGameInfo" class="save-button">保存</button>
        <button type="button" @click="cancel" class="cancel-button">取消</button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.change-game-info {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.game-form {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 表单组：标签左 + 输入框右 */
.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.form-group label {
  width: 100px; /* 标签固定宽度，确保对齐 */
  margin-right: 10px;
  font-weight: bold;
  color: #555;
}

.form-control {
  flex: 1; /* 输入框/文本域占剩余宽度 */
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #31B310;
  box-shadow: 0 0 5px rgba(49, 179, 16, 0.3);
}

/* 时间选择“田字格”布局 */
.time-grid {
  display: grid;
  grid-template-columns: 1fr 1fr; /* 2列 */
  grid-template-rows: auto auto;  /* 2行 */
  gap: 20px; /* 格子之间的间距 */
  margin-bottom: 20px;
}

/* 操作按钮组 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.save-button, .cancel-button {
  padding: 12px 30px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-button {
  background: linear-gradient(to right, #31B310, #2a990e);
  color: white;
}

.cancel-button {
  background: #95a5a6;
  color: white;
}

.save-button:hover, .cancel-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>